import {computed, designComponent, PropType, useClasses} from "@peryl/react-compose";
import './MicroList.scss';
import {iMicroConfig, iMicroPageMeta, iMicroTokenInfo, isPathMatchMicroConfig} from "@peryl/micro-web";
import {microApp} from "../microApp";
import {MicroItem} from "./MicroItem";
import {insertSort} from "@peryl/utils/insertSort";

/**
 * 渲染所有的子应用
 * @author  韦胜健
 * @date    2024/1/31 17:58
 */
export const MicroList = designComponent({
  name: 'router-render',
  props: {
    tokenInfo: { type: Object as PropType<iMicroTokenInfo>, required: true }
  },
  setup({ props }) {

    const classes = useClasses(() => [
      'router-render',
    ]);

    let prevMicroConfigs: iMicroConfig[] = [];

    /**
     * 管理microConfig的加载顺序，先打开的在前面，后打开的在后面
     * @author  韦胜健
     * @date    2024.7.4 15:50
     */
    const microConfigSeqManager = (() => {
      const cache = {} as Record<string, number | undefined>;
      const nextSeq = (() => {
        let count = 1;
        return () => count++;
      })();
      const record = (microConfigId: string) => {if (!cache[microConfigId]) {cache[microConfigId] = nextSeq();}};
      return {
        record,
        getSeq: (microConfigId: string): number => cache[microConfigId]!
      };
    })();

    const renderMicroData = computed(() => {

      const initPages = microApp.state.tabs.reduce((prev, item) => {
        prev.push(...item.pages.filter(i => i.init));
        return prev;
      }, [] as iMicroPageMeta[]);

      /*要渲染的page所属的子应用*/
      let microConfigs: iMicroConfig[] = [];
      /*没有子应用处理的page*/
      const noMicroPageMetas: iMicroPageMeta[] = [];
      let currentMicroConfig = undefined as undefined | iMicroConfig;

      initPages.forEach(pageMeta => {
        const matchMicroConfig = microApp.state.microConfigs.find(i => isPathMatchMicroConfig(pageMeta.path, i));
        if (pageMeta.show) {
          currentMicroConfig = matchMicroConfig;
        }
        if (!matchMicroConfig) {
          noMicroPageMetas.push(pageMeta);
        } else {
          if (!microConfigs.find(i => i.id === matchMicroConfig.id)) {
            microConfigs.push(matchMicroConfig);
          }
        }
      });

      /*保留已经加载过的子应用*/
      const emptyMicros = prevMicroConfigs.filter(i => microConfigs.findIndex(j => j.id === i.id) === -1);
      microConfigs = [...emptyMicros, ...microConfigs];
      prevMicroConfigs = microConfigs;

      microConfigs.forEach(i => microConfigSeqManager.record(i.id));

      return { microConfigs, noMicroPageMetas, currentMicroConfig };
    });

    return () => (
      <div className={classes.value}>
        {insertSort(renderMicroData.value.microConfigs, (a, b) => microConfigSeqManager.getSeq(a.id) > microConfigSeqManager.getSeq(b.id)).map(microConfig => {
          const active = microConfig.id === renderMicroData.value.currentMicroConfig?.id;
          return <MicroItem tokenInfo={props.tokenInfo} microConfig={microConfig} key={microConfig.id} active={active} data-active={String(active)}/>;
        })}
        {renderMicroData.value.noMicroPageMetas.map(noMicroPageMeta => {
          return (
            <div key={noMicroPageMeta.id} data-active={String(noMicroPageMeta.show)}>
              {`未定义子应用处理页面路径：${noMicroPageMeta.path}`}
            </div>
          );
        })}
      </div>
    );
  },
});
